﻿using System.Linq;
using System.Threading.Tasks;

namespace Sidvall.IdentityManager.Data.Entity.Model.StorageManagers
{
    public static partial class AspNetUsersManager
    {
        #region Partial Members

        #region OnBeforeGetItems

        static partial void OnBeforeGetItems(StorageManager storageManager, Sidvall.Business.DataPortalContext<IAspNetUsers, Sidvall.Data.FetchListCriteria<Fields.AspNetUsersField, Relations.AspNetUsersRelation>> dataPortalContext)
        {
            dataPortalContext.Tasks.Add(OnBeforeGetItemsTask(storageManager, dataPortalContext));
        }
        private static async Task OnBeforeGetItemsTask(StorageManager storageManager, Sidvall.Business.DataPortalContext<IAspNetUsers, Sidvall.Data.FetchListCriteria<Fields.AspNetUsersField, Relations.AspNetUsersRelation>> dataPortalContext)
        {
            switch (dataPortalContext.OperationContext.CriteriaId)
            {
                case ParameterManager.FindUsersFromLoginCommandId:
                    await LoadItemsAsync(storageManager, dataPortalContext).ConfigureAwait(false);
                    dataPortalContext.Result = Sidvall.Business.DataPortalResult.Ok;
                    break;
                default:
                    break;
            }
        }

        #endregion

        #endregion
        #region Private Members

        #region LoadItemsAsync

        private static async Task LoadItemsAsync(StorageManager storageManager, Sidvall.Business.DataPortalContext<IAspNetUsers, Sidvall.Data.FetchListCriteria<Fields.AspNetUsersField, Relations.AspNetUsersRelation>> dataPortalContext)
        {
            System.Data.Entity.Infrastructure.DbQuery<global::Sidvall.IdentityManager.Data.Entity.Entities.AspNetUsers> dbQuery;
            string loginProvider, providerKey;

            loginProvider = dataPortalContext.Parameters.ValueToString(ParameterManager.LoginProviderParameterKey, null);
            providerKey = dataPortalContext.Parameters.ValueToString(ParameterManager.ProviderKeyParameterKey, null);

            dbQuery = storageManager.ObjectContext.AspNetUsers.AsNoTracking();
            var query = (from o in dbQuery
                         join r in storageManager.ObjectContext.AspNetUserLogins on o.Id equals r.UserId
                         where r.LoginProvider.Equals(loginProvider, System.StringComparison.OrdinalIgnoreCase) && r.ProviderKey.Equals(providerKey, System.StringComparison.OrdinalIgnoreCase)
                         select o);
            var entityItems = new global::Sidvall.IdentityManager.Data.Entity.Entities.AspNetUsersCollection();
            await Sidvall.IdentityManager.Data.Entity.SystemContext.Current.DataManager.LoadEntityObjectsAsync(query, entityItems, Sidvall.Data.DataRowState.Unchanged).ConfigureAwait(false);
            dataPortalContext.ResultValueList = entityItems;
        }

        #endregion

        #endregion
    }
}